import Vue from 'vue';
import Vuex from 'vuex';

// 引入vuex持久化方法createPersistedState
import createPersistedState from 'vuex-persistedstate';
import apiUrl from "@/api/apiUrl.js";
import config from '@/api/config';
import * as dd from 'dingtalk-jsapi'

Vue.use(Vuex);
// 登录验证
export default new Vuex.Store({
  state: {
    // 多语言
    language: config.language,
    languagesArr: config.languages,
    languagesCurrent: config.languagesCurrent,
    // code手机前缀列表
    codeList: config.codeList,
    codeCurrent: config.codeCurrent,

    // 用户信息
    user: {
      authlist: [],
      userInfo: {},
      roleInfo: {},
    },
    // 钉钉信息
    dingInfo: {},
  },
  mutations: {
    // 设多语言
    saveLanguagesArr(state,arr){
      state.languagesArr = arr;
      // console.log('state.languagesArr',state.languagesArr)
    },
    saveLanguagesCurrent(state,index){
      state.languagesCurrent = index
      // console.log('state.languagesCurrent',state.languagesCurrent)
    },

      saveMember(state, data) {
        state.user = data;
        localStorage.setItem("userInfo", data);
        localStorage.setItem("dingToken", data.id);
      },
      // 退出
      clearMember(state) {
          if(!state.user) return
          state.user = "";
          localStorage.removeItem("userInfo");
          localStorage.removeItem("dingToken");
      },
      // 物料列表
      setMateriallist(state, materiallist) {
        state.materiallist = materiallist;
      },
      // 钉钉信息
      saveDingInfo(state, dingInfo) {
        state.dingInfo = dingInfo;
        localStorage.setItem("dingInfo", dingInfo);
      },
      //
      clearDingInfo(state) {
        state.dingInfo = {};
        localStorage.setItem("dingInfo", "");
      },
  },
  actions:{
    // 用户信息
    async getMemberInfo({
        commit,
        state
      }, parm = {}) {
      if (state.user) {
        //已经登录过
        apiUrl.userInfo({
          id: state.user.id,
          ...parm
        }).then(res => {
          const { code, data={} } = res
          // console.log('data', data)
          if (code == 0) {
            commit('saveMember', data);
          }else{
            commit('clearMember');
          }
        })
      } else {
        // 未登录
      }
    },
    // 钉钉jsapi授权
    nailConfiguration({
       commit,
       state
     }, parm = {}) {
      return new Promise((resolve, reject) => {
          dd.ready(() => {
            apiUrl.nailConfiguration({
              data: {
                ...parm
              }
            }, 'POSTCRM').then(res => {
              console.log('nailConfiguration res', res)
              const { data } = res
              if(data){
                // 新旧jsapi
                const jsapilist = [
                  'chooseDepartments',
                  'complexChoose',
                  'chooseChat'

                  // 'biz.contact.departmentsPicker',
                  // 'biz.contact.complexPicker',
                  // 'biz.chat.chooseConversationByCorpId'
                ]
                dd.config({
                  agentId: data.agentId,
                  corpId: data.corpId, // 必填，企业ID
                  timeStamp: data.timestamp, // 必填，生成签名的时间戳
                  nonceStr: data.nonceStr, // 必填，生成签名的随机串
                  signature: data.signature, // 必填，签名
                  jsApiList: jsapilist // 必填，需要使用的jsapi列表，注意：不要带dd。
                })
                dd.error(function (err) {
                    alert('dd error: ' + JSON.stringify(err));
                })//该方法必须带上，用来捕获鉴权出现的异常信息，否则不方便排查出现的问题
              }
              resolve(res)
            }).catch(error => {
              reject(error)
            })
          })
      })
    },
    // 钉钉授权登录
    getAuthorize({
       commit,
       state
     }, parm = {}) {
      return new Promise((resolve, reject) => {
        apiUrl.getAuthorize({
          data: {
            ...parm
          }
        }, 'POST').then(res => {
          console.log('getAuthorize res', res)
          const { code, data = {} } = res
          if (code == 0) {
            commit('saveMember', data);
          }else{
            commit('clearMember');
          }
          resolve(res)
        }).catch(error => {
          // commit('clearMember');
          reject(error)
        })
      })
    },
    // 获取模块列表
    async moduleList({
     commit,
     state
    }, parm = {},method="POST") {
      return new Promise((resolve, reject) => {
        apiUrl.moduleList(parm,method)
          .then(res => {
            resolve(res)
          }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取多语言列表
    async languageListGet({
       commit,
       state
     }, parm = {},method="POST") {
      return new Promise((resolve, reject) => {
        apiUrl.languageListGet(parm,method)
          .then(res => {
            resolve(res)
          }).catch(error => {
            reject(error)
          })
      })
    },
    // 退出登录
    async logOut({
      commit,
      state
    }, parm = {}) {
      return new Promise((resolve) => {
        if (state.user) {
          //已经登录过
          apiUrl.logOut({
            userId: state.user.id,
            ...parm
          }).then(res => {
            resolve(res)
          })
        }
        resolve()
      })
    },
  },
  getters:{
    // 用户功能权限列表
    userAuthList: state => state.user.authlist || [],
    // 用户个人信息
    userInfo: state => state.user.userInfo || {},
    // 用户角色信息
    roleInfo: state => state.user.roleInfo || {},
    // 当前语言参数
    languageAttribute(state) {
      if(state.languagesArr&&state.languagesArr.length>0){
        return state.languagesArr[state.languagesCurrent].attribute;
      }
      return config.languageAttribute
    },
  },
  plugins: [createPersistedState({
    storage: window.sessionStorage,
    reducer(val) {
      return {
        // 只储存state中的user
        user: val.user,
        materiallist: val.materiallist,
        dingInfo: val.dingInfo,
        // 多语言
        languagesArr:val.languagesArr,
        languagesCurrent: val.languagesCurrent,
        language:val.language,
        // code手机前缀列表
        codeCurrent:val.codeCurrent,
        codeList: val.codeList,
        userInfo: val.userInfo,
        userAuthList: val.userAuthList,
        languageAttribute: val.languageAttribute,
      }
    }
  })],
})
